'use client'

import { useMemo, useState } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Progress } from '@/components/ui/progress'
import {
  IconHome,
  IconMap,
  IconPlayerPlay,
  IconAlertTriangle,
  IconUser,
  IconClock,
  IconFlame,
  IconRoute,
  IconBell,
  IconDownload,
  IconCheck
} from '@tabler/icons-react'

export default function MobileApp() {
  const [tab, setTab] = useState('home')

  return (
    <div className="min-h-screen bg-white">
      <div className="sticky top-0 z-10 bg-white/90 backdrop-blur border-b">
        <div className="h-12 px-4 flex items-center justify-between">
          <div className="font-semibold">医院数字孪生</div>
          <Badge variant="outline" className="text-xs">Demo</Badge>
        </div>
      </div>

      <Tabs value={tab} onValueChange={setTab} className="w-full">
        <TabsContent value="home" className="p-4 space-y-4">
          <HomeTab />
        </TabsContent>
        <TabsContent value="map" className="p-4 space-y-4">
          <MapTab />
        </TabsContent>
        <TabsContent value="simulate" className="p-4 space-y-4">
          <SimulateTab />
        </TabsContent>
        <TabsContent value="alerts" className="p-4 space-y-4">
          <AlertsTab />
        </TabsContent>
        <TabsContent value="me" className="p-4 space-y-4">
          <MeTab />
        </TabsContent>

        <div className="h-14" />

        <div className="fixed bottom-0 inset-x-0 border-t bg-white">
          <TabsList className="grid grid-cols-5 h-14">
            <TabsTrigger value="home" className="flex flex-col gap-1">
              <IconHome className="w-5 h-5" />
              <span className="text-xs">主页</span>
            </TabsTrigger>
            <TabsTrigger value="map" className="flex flex-col gap-1">
              <IconMap className="w-5 h-5" />
              <span className="text-xs">导航</span>
            </TabsTrigger>
            <TabsTrigger value="simulate" className="flex flex-col gap-1">
              <IconPlayerPlay className="w-5 h-5" />
              <span className="text-xs">仿真</span>
            </TabsTrigger>
            <TabsTrigger value="alerts" className="flex flex-col gap-1">
              <IconAlertTriangle className="w-5 h-5" />
              <span className="text-xs">告警</span>
            </TabsTrigger>
            <TabsTrigger value="me" className="flex flex-col gap-1">
              <IconUser className="w-5 h-5" />
              <span className="text-xs">我的</span>
            </TabsTrigger>
          </TabsList>
        </div>
      </Tabs>
    </div>
  )
}

function HomeTab() {
  const kpis = [
    { title: '平均等待', value: '32分', status: 'warning' },
    { title: '峰值密度', value: '3.8/m²', status: 'critical' },
    { title: '瓶颈走廊', value: 3, status: 'warning' },
    { title: '今日告警', value: 5, status: 'critical' }
  ]

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>关键KPI</CardTitle>
          <CardDescription>今日概览</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 gap-3">
            {kpis.map((k) => (
              <div key={k.title} className="p-3 border rounded-lg">
                <div className="text-xs text-gray-500">{k.title}</div>
                <div className="text-lg font-semibold">{k.value}</div>
                <Badge variant={k.status === 'critical' ? 'destructive' : 'secondary'} className="mt-1">{k.status === 'critical' ? '高' : '中'}</Badge>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2"><IconFlame className="w-4 h-4" />热力缩略</CardTitle>
          <CardDescription>点击前往三维查看</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-12 gap-1 aspect-[12/6] rounded bg-gray-50 p-2">
            {Array.from({ length: 72 }).map((_, i) => (
              <div key={i} className={`h-3 rounded ${i % 11 === 0 ? 'bg-red-500/80' : i % 5 === 0 ? 'bg-yellow-500/70' : 'bg-blue-500/60'}`} />
            ))}
          </div>
          <div className="flex justify-end mt-3">
            <Button size="sm" variant="outline" onClick={() => window.open('/dashboard', '_blank')}>进入看板</Button>
          </div>
        </CardContent>
      </Card>

      <div className="grid grid-cols-3 gap-3">
        <Button className="h-20 flex flex-col gap-1"><IconPlayerPlay className="w-5 h-5" />启动仿真</Button>
        <Button variant="outline" className="h-20 flex flex-col gap-1"><IconRoute className="w-5 h-5" />场景预设</Button>
        <Button variant="outline" className="h-20 flex flex-col gap-1"><IconBell className="w-5 h-5" />应急疏散</Button>
      </div>
    </>
  )
}

function MapTab() {
  const levels = ['L1', 'L2', 'L3']
  const [level, setLevel] = useState('L1')

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>楼层与路径</CardTitle>
          <CardDescription>模拟楼层与路径查询</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex gap-2 mb-3">
            {levels.map(l => (
              <Button key={l} size="sm" variant={l === level ? 'default' : 'outline'} onClick={() => setLevel(l)}>{l}</Button>
            ))}
          </div>
          <div className="rounded-lg border bg-gray-50 aspect-video flex items-center justify-center text-gray-500">
            地图占位（高德/三维）
          </div>
          <div className="mt-3 text-sm text-gray-600">ETA: 6 分钟 · 模式: 普通</div>
        </CardContent>
      </Card>
    </>
  )
}

function SimulateTab() {
  const [running, setRunning] = useState(false)
  const [progressValue, setProgressValue] = useState(0)

  const start = () => {
    setRunning(true)
    setProgressValue(0)
    const timer = setInterval(() => {
      setProgressValue((v) => {
        const nv = Math.min(100, v + Math.random() * 12)
        if (nv >= 100) {
          clearInterval(timer)
          setRunning(false)
        }
        return nv
      })
    }, 500)
  }

  const metrics = useMemo(() => (
    [
      { name: 'avgWait', label: '平均等待', value: '31分', trend: '+12%' },
      { name: 'maxDensity', label: '峰值密度', value: '3.6/m²', trend: '-8%' },
      { name: 'conflictRate', label: '冲突率', value: '1.2%', trend: '-0.3%' }
    ]
  ), [])

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>参数快调</CardTitle>
          <CardDescription>到达率 / 服务时长（模拟）</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            <div>
              <div className="text-xs text-gray-500 mb-1">到达率</div>
              <Progress value={60} />
            </div>
            <div>
              <div className="text-xs text-gray-500 mb-1">服务时长</div>
              <Progress value={40} />
            </div>
            <Button onClick={start} disabled={running} className="w-full">
              <IconPlayerPlay className="w-4 h-4 mr-1" />{running ? '运行中...' : '启动仿真'}
            </Button>
            <div className="flex items-center gap-2 text-sm text-gray-600">
              <IconClock className="w-4 h-4" /> 进度
            </div>
            <Progress value={progressValue} />
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>KPI 指标</CardTitle>
          <CardDescription>模拟结果摘要</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 gap-3">
            {metrics.map(m => (
              <div key={m.name} className="p-3 border rounded-lg">
                <div className="text-xs text-gray-500">{m.label}</div>
                <div className="text-lg font-semibold">{m.value}</div>
                <div className="text-xs text-green-600">{m.trend}</div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>
    </>
  )
}

function AlertsTab() {
  const alerts = [
    { id: 'a1', type: '拥挤', level: '高', loc: '急诊走廊', time: '2分钟前', status: '未处理' },
    { id: 'a2', type: '冲突', level: '中', loc: '药房', time: '8分钟前', status: '未处理' },
    { id: 'a3', type: '过载', level: '低', loc: '电梯间', time: '20分钟前', status: '已处理' }
  ]

  return (
    <Card>
      <CardHeader>
        <CardTitle>告警列表</CardTitle>
        <CardDescription>模拟订阅：高/中/低</CardDescription>
      </CardHeader>
      <CardContent>
        <div className="space-y-2">
          {alerts.map(a => (
            <div key={a.id} className="flex items-center justify-between p-3 border rounded-lg">
              <div>
                <div className="flex items-center gap-2">
                  <Badge variant={a.level === '高' ? 'destructive' : a.level === '中' ? 'secondary' : 'outline'}>{a.level}</Badge>
                  <span className="font-medium">{a.type}</span>
                </div>
                <div className="text-xs text-gray-500">{a.loc} · {a.time}</div>
              </div>
              <Button size="sm" variant="outline">确认</Button>
            </div>
          ))}
        </div>
      </CardContent>
    </Card>
  )
}

function MeTab() {
  const items = [
    { k: '角色', v: 'manager' },
    { k: '机构', v: 'HOSP1' },
    { k: '离线包', v: '已安装' }
  ]

  return (
    <>
      <Card>
        <CardHeader>
          <CardTitle>我的</CardTitle>
          <CardDescription>账号与组织、权限与消息</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-2">
            {items.map(i => (
              <div key={i.k} className="flex items-center justify-between p-3 border rounded-lg">
                <div className="text-sm text-gray-600">{i.k}</div>
                <div className="text-sm font-medium">{i.v}</div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      <div className="grid grid-cols-2 gap-3">
        <Button className="h-12"><IconDownload className="w-4 h-4 mr-1" />下载离线包</Button>
        <Button variant="outline" className="h-12"><IconCheck className="w-4 h-4 mr-1" />二次校验</Button>
      </div>
    </>
  )
}


